package com.aaa.mrcai.aop;

import cn.hutool.core.date.DateUtil;
import com.aaa.mrcai.annotion.AAALog;
import com.aaa.mrcai.mapper.LogMapper;

import com.aaa.mrcai.pojo.entity.EmpInfo;
import com.aaa.mrcai.pojo.entity.LogData;
import com.aaa.mrcai.result.AjaxResult;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Arrays;



/**
 * @ Author: Lining
 * @ Date: 2021/12/19 17:56
 */
@Component
@Aspect
public class HahaAOP {

    @Autowired
    private LogMapper mapper;
    /**
     * id  username msg result  ipaddr  data
     * */
    public void before(){
    }

    @AfterReturning(pointcut = "@annotation(aaaLog)", returning = "result")
    public void after(JoinPoint joinPoint, AAALog aaaLog, AjaxResult result){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        //获取msg 添加区域等操作
        String msg = aaaLog.value();
        //获取 0 或 1
        Integer code = result.getCode();
        //获取ip地址
        String ipaddr = request.getRemoteAddr();
        String time = DateUtil.now();
        EmpInfo empInfo = (EmpInfo) request.getSession().getAttribute("emp");
        String username = empInfo.getEname();
        //获取参数  data
        Object[] data = joinPoint.getArgs();
        LogData logData = new LogData(null,username,msg,code,time,ipaddr, Arrays.toString(data));
        mapper.addLog(logData);
    }
}
